<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="/webjars/jquery/jquery.min.js"></script>
    <script src="/webjars/sockjs-client/sockjs.min.js"></script>
    <script src="/webjars/stomp-websocket/stomp.min.js"></script>
</head>
<body>
<h1>群聊</h1>
<div id="result">

</div>
<div>
    <table>
        <tr>
            <td>姓名：</td>
            <td><input type="text" id="name"></td>
        </tr>
        <tr>
            <td>消息：</td>
            <td><input type="text" id="content"></td>
        </tr>
        <tr>
            <td>
                <button onclick="sendClick()">发送</button>
            </td>
        </tr>
    </table>
</div>
<script>
    var stomp;

    /**
     * 初始化 WebSocket 链接
     */
    function initCon() {
        var sockjs = new SockJS("/myws/ep");
        stomp = Stomp.over(sockjs);
        stomp.connect({}, function (success) {
            stomp.subscribe('/topic/greeting', function (msg) {
                var body = msg.body;
                var m = JSON.parse(body);
                // language=HTML
                $("#result").append('<div>' + m.name + ':' + m.content + '</div>');
            });
        });
    }

    function sendClick() {
        let name = $("#name").val();
        let content = $("#content").val();
        let msg = {name: name, content: content}
        stomp.send("/greeting", {}, JSON.stringify(msg));
    }

    initCon();
</script>
</body>
</html>